//
//  main.cpp
//  lua_call_cpp
//
//  Created by Ge Jian Feng on 14-5-18.
//  Copyright (c) 2014年 Ge Jian Feng. All rights reserved.
//

#include <iostream>

#ifdef __cplusplus
extern "C" {
#endif
    
#include "Lua/lua.h"
#include "Lua/luaconf.h"
#include "Lua/lauxlib.h"
#include "Lua/lualib.h"
    
#ifdef __cplusplus
}
#endif

void registerFunctions(lua_State *L);
int multi(lua_State *L);

int main(int argc, const char * argv[])
{
    lua_State *L = luaL_newstate();
    luaL_openlibs(L);
    
    registerFunctions(L);
    
    luaL_dofile(L, "main.lua");

    lua_close(L);
    
    return 0;
}

void registerFunctions(lua_State *L)
{
    lua_register(L, "multi", multi);
}

int multi(lua_State *L)
{
    double result = 0;
    double data1 = 0;
    double data2 = 0;
    
    if (lua_isnumber(L, -1) == false) {
        lua_pushstring(L, "Incorrect first argument to 'multi'");
        lua_error(L);
    }
    else {
        data1 = lua_tonumber(L, -1);
    }
    
    if (lua_isnumber(L, -2) == false) {
        lua_pushstring(L, "Incorrect second argument to 'multi'");
        lua_error(L);
    }
    else {
        data2 = lua_tonumber(L, -2);
    }
    
    result = data1 * data2;
    lua_pushnumber(L, result);
    
    return 1;
}

